package com.lemt.sunmao.service.impl;

import com.alibaba.fastjson.JSON;
import com.lemt.sunmao.constant.EsConstant;
import com.lemt.sunmao.domain.User;
import com.lemt.sunmao.mapper.UserMapper;
import com.lemt.sunmao.service.EsService;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Service
public class EsServiceImpl implements EsService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    public Boolean parseUser() throws IOException {
        System.out.println("将大学java课程信息放入es索引中");

        List<User> users = userMapper.selectAll();
        System.out.println("查所有用户"+users);
        // 批量插入数据
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("2m");

        for (int i = 0; i < users.size(); i++) {
            bulkRequest.add(
                    new IndexRequest(EsConstant.USER_INDEX)
                            .source(JSON.toJSONString(users.get(i)), XContentType.JSON)
            );
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        return !bulk.hasFailures();
    }
}
